package com.iotboss.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.iotboss.common.constant.Constants;
import com.iotboss.common.core.domain.AjaxResult;
import com.iotboss.common.core.domain.entity.SysMenu;
import com.iotboss.common.core.domain.entity.SysUser;
import com.iotboss.common.utils.AesEncryptUtil;
import com.iotboss.common.utils.SecurityUtils;
import com.iotboss.framework.web.service.SysLoginService;
import com.iotboss.framework.web.service.SysPermissionService;
import com.iotboss.system.service.ISysDeptService;
import com.iotboss.system.service.ISysMenuService;
import com.iotboss.system.service.ISysUserService;
import com.iotboss.web.core.config.MyBaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author iotboss
 */
@RestController
public class SysLoginController extends MyBaseController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 登录方法
     *
     * @param 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public String login(@RequestBody String Pstr) {
        HashMap<String, Object> Parammap = new HashMap<String, Object>();
        if (Pstr != null) {
            Pstr = Pstr.replace("%2F", "/");//转义 /
        }
        try {
            Pstr = AesEncryptUtil.desEncrypt(Pstr);
            Parammap.putAll(JSON.parseObject((String) Pstr));//参数解析 parammap

            AjaxResult ajax = AjaxResult.success();
            // 生成令牌
            String token = loginService.login(Parammap.get("username").toString(), Parammap.get("password").toString(), Parammap.get("code").toString(),
                    Parammap.get("uuid").toString(), Parammap.get("dept").toString());
            ajax.put(Constants.TOKEN, token);
//            return ajax;
            return MyRetunSuccess(ajax, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //个人登录拦截（非关联企业）
        if (user.getDeptId() == null) {
            return AjaxResult.error("该用户无所属企业");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    //根据登录信息查询该用户下的所有企业
    @PostMapping(value = "/getCustomUser")
    public String getCustomUser(@RequestBody String Pstr) {
//        Object userName = map.get("userName");
//        Object pwd = map.get("pwd");
//        SysUser sysUser = sysUserService.selectUserByUserName(userName.toString());
//        this.matchesPassword(sysUser.getPassword(), pwd.toString());
//
//        SysDept sysDept = new SysDept();
//        sysDept.setPhone(userName.toString());
//
        HashMap<String, Object> Parammap = new HashMap<String, Object>();
        if (Pstr != null) {
            Pstr = Pstr.replace("%2F", "/");//转义 /
        }
        try {
            Pstr = AesEncryptUtil.desEncrypt(Pstr);
            Parammap.putAll(JSON.parseObject((String) Pstr));//参数解析 parammap
            Object userName = Parammap.get("userName");
            Object pwd = Parammap.get("pwd");
            SysUser sysUser = sysUserService.selectUserByUserName(userName.toString());
            this.matchesPassword(sysUser.getPassword(), pwd.toString());
            //权限校验通过 查询 所有 dept及上级企业
            return MyRetunSuccess(deptService.getDeptCopy(Parammap), "操作成功！");
        } catch (Exception e) {

        }
        return null;
    }

    //根据登录信息查询该用户下的所有企业
    @PostMapping(value = "/parentId")
    public String getPreantId(@RequestBody String Pstr) {
        HashMap<String, Object> Parammap = new HashMap<String, Object>();
        if (Pstr != null) {
            Pstr = Pstr.replace("%2F", "/");//转义 /
        }
        try {
            Pstr = AesEncryptUtil.desEncrypt(Pstr);
            Parammap.putAll(JSON.parseObject((String) Pstr));//参数解析 parammap
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
